import {FC, useState} from 'react';
import Taro, { useDidHide, useReady } from '@tarojs/taro';
import { View } from '@tarojs/components';
import {Button} from 'antd-mobile';
import {currentTimeFormat} from '@/utils/common';
import styles from './index.module.lexx';

const IhuAudio: FC = () => {
    // 音频总时长
    const [allDuration, setAllDuration] = useState('00:00');
    // 进度条时间
    const [currentTime, setCurrentTime] = useState('00:00');
    // 进度条的值
    const [progressValue, setProgressValue] = useState(0);
    const innerAudioContext = Taro.createInnerAudioContext();
    innerAudioContext.autoplay = false;
    innerAudioContext.src = 'https://storage.360buyimg.com/jdrd-blog/27.mp3';

    innerAudioContext.onEnded(() => {
        console.log('播放完毕');
    });
    innerAudioContext.onError((res) => {
        console.log(res.errMsg);
        console.log(res.errCode);
    });
    // 监听音频播放进度更新事件
    innerAudioContext.onTimeUpdate(() => {
        // debugger
        setCurrentTime(currentTimeFormat(innerAudioContext.currentTime));
        setProgressValue(
            Math.floor((innerAudioContext.currentTime / innerAudioContext.duration) * 1000) / 10
        );
    });

    const handleClick = () => {
        innerAudioContext.play();
        console.log(innerAudioContext.currentTime);
        console.log(innerAudioContext.duration);
    };
    const handlePause = () => {
        innerAudioContext.pause();
    };
    useReady(() => {
        innerAudioContext.onCanplay(() => {
            setTimeout(() => {
                setAllDuration(currentTimeFormat(innerAudioContext.duration));
            }, 300);
        });
        innerAudioContext.onStop(() => {
            innerAudioContext.destroy();
        });
    });
    useDidHide(() => {
        innerAudioContext.stop();
    });
    // 进度条拖动时
    const sliderChange = value => {
        innerAudioContext.pause();
        const currentPosition = Math.floor((innerAudioContext.duration * value) / 100);
        innerAudioContext.seek(currentPosition);
        innerAudioContext.play();
    };
    return (
        <>
            <Button color='primary' onClick={handleClick}>播放</Button>
            <View>进度值：{progressValue}</View>
            <View>当前时间：{currentTime}</View>
            <View>总时间：{allDuration}</View>
            <Button color='primary' onClick={handlePause}>暂停</Button>
        </>
    );
}
export default IhuAudio;